<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="部门名称">
        <el-input v-model="queryParams.name" placeholder="请输入部门名称" clearable @keyup.enter="getList" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="open=true">新增</el-button>
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" v-if="refreshTable" :data="counter.depsTree" row-key="_id" :default-expand-all="isExpandAll" :tree-props="{ children: 'children'}">
      <el-table-column prop="name" label="部门名称"></el-table-column>
      <el-table-column prop="leader" label="负责人"></el-table-column>
      <el-table-column prop="phone" label="联系电话"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="sort" label="排序"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="created_at_str" min-width="120" />
      <el-table-column label="操作" align="center" min-width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button v-if="scope.row.parentId != 0" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog title="新增/编辑部门" v-model="open" width="600px" append-to-body :before-close="handleClose">
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级部门" prop="parentId" v-if="form.parentId">
          <depTreeSelect v-model="form.parentId"></depTreeSelect>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="显示排序">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="editLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();

const deptList = ref([]);
let depTree = ref([]);
const open = ref(false);
let loading = ref(false);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
let editLoading = ref(false);

let queryParams = ref({
  name: "",
});
let form = ref({
  _id: null,
  parentId: null,
  name: null,
  sort: 0,
  leader: null,
  phone: null,
  email: null,
  children: [],
});
let rules = ref({
  parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
  name: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  getList();
});

/** 查询部门列表 */
async function getList() {
  try {
    loading.value = true;
    deptList.value = await proxy.$apis.depList(queryParams.value);
    counter.depts = [...deptList.value];
  } catch (error) {
  } finally {
    loading.value = false;
  }
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    name: "",
  };
  getList();
}
/** 新增按钮操作 */
function handleAdd(row) {
  form.value.parentId = row._id;
  open.value = true;
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  form.value = proxy.$utils.formatFunction(row, { ...form.value });
  open.value = true;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) save();
  });
}
let handleClose = () => {
  form.value = {
    _id: null,
    parentId: null,
    name: null,
    sort: 0,
    leader: null,
    phone: null,
    email: null,
    children: [],
  };
  proxy.$refs.deptRef.resetFields();
  getList();
  open.value = false;
};
let save = async () => {
  try {
    editLoading.value = true;
    await proxy.$apis.depHandle(form.value);
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    editLoading.value = false;
  }
};
/** 删除按钮操作 */
async function handleDelete(row) {
  let resp = await proxy.$utils.confirmTips(
    '是否确认删除名称为"' + row.name + '"的数据项?'
  );
  if (!resp) return;
  await proxy.$apis.delDept({ ids: row._id });
  getList();
  proxy.$modal.msgSuccess("删除成功");
}
</script>
